package com.edu.labmanager.controller;


import com.edu.labmanager.entity.College;
import com.edu.labmanager.service.ICollegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 * 学院表，存储学校下属各学院的基本信息 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-06-15
 */
@Controller
@RequestMapping("/college")
public class CollegeController {

    @Autowired
    private ICollegeService collegeService;

    // 查询所有学院
    @GetMapping("/")
    @PreAuthorize("hasRole('admin')")
    public String listColleges(Model model) {
        List<College> colleges = collegeService.list();
        model.addAttribute("colleges", colleges);

        return "college-list"; // 对应 templates/college-list.html
    }

    // 跳转到新增页面
    @GetMapping("/add")
    @PreAuthorize("hasRole('admin')")
    public String showAddForm(Model model) {
        model.addAttribute("college", new College());
        return "college-form";
    }

    // 提交新增
    @PostMapping("/add")
    @PreAuthorize("hasRole('admin')")
    public String addCollege(@ModelAttribute College college) {
        collegeService.save(college);
        return "redirect:/college/";
    }

    // 跳转到编辑页面
    @GetMapping("/edit/{id}")
    @PreAuthorize("hasRole('admin')")
    public String showEditForm(@PathVariable Integer id, Model model) {
        College college = collegeService.getById(id);
        model.addAttribute("college", college);
        return "college-form";
    }

    // 提交更新
    @PostMapping("/update")
    @PreAuthorize("hasRole('admin')")
    public String updateCollege(@ModelAttribute College college) {
        collegeService.updateById(college);
        return "redirect:/college/";
    }

    // 删除学院
    @GetMapping("/delete/{id}")
    @PreAuthorize("hasRole('admin')")
    public String deleteCollege(@PathVariable Integer id) {
        collegeService.removeById(id);
        return "redirect:/college/";
    }
}
